import http from 'http';
import https from 'https';

// 配置代理
const proxyOptions = {
  host: 'localhost',
  port: 12300
};

// 测试不同的HTTP方法
const testRequests = [
  {
    method: 'GET',
    url: 'http://httpbin.org/get',
    data: null
  },
  {
    method: 'POST',
    url: 'http://httpbin.org/post',
    data: JSON.stringify({ test: 'POST请求测试', timestamp: Date.now() })
  },
  {
    method: 'PUT',
    url: 'http://httpbin.org/put',
    data: JSON.stringify({ test: 'PUT请求测试', timestamp: Date.now() })
  },
  {
    method: 'PATCH',
    url: 'http://httpbin.org/patch',
    data: JSON.stringify({ test: 'PATCH请求测试', timestamp: Date.now() })
  },
  {
    method: 'DELETE',
    url: 'http://httpbin.org/delete',
    data: null
  }
];

async function sendRequest(testConfig) {
  return new Promise((resolve, reject) => {
    console.log(`🚀 发送 ${testConfig.method} 请求到: ${testConfig.url}`);

    // 直接通过代理发送请求
    const options = {
      hostname: proxyOptions.host,
      port: proxyOptions.port,
      path: testConfig.url, // 完整URL作为path
      method: testConfig.method,
      headers: {
        'Host': new URL(testConfig.url).host,
        'User-Agent': 'NetworkFirewall-Test/1.0',
        'Accept': 'application/json',
        'Connection': 'close'
      }
    };

    if (testConfig.data) {
      options.headers['Content-Type'] = 'application/json';
      options.headers['Content-Length'] = Buffer.byteLength(testConfig.data);
    }

    const req = http.request(options, (res) => {
      let data = '';
      
      res.on('data', (chunk) => {
        data += chunk;
      });
      
      res.on('end', () => {
        console.log(`✅ ${testConfig.method} 请求完成 - 状态码: ${res.statusCode}`);
        resolve({
          method: testConfig.method,
          statusCode: res.statusCode,
          headers: res.headers,
          data: data
        });
      });
    });

    req.on('error', (error) => {
      console.error(`❌ ${testConfig.method} 请求失败:`, error.message);
      reject(error);
    });

    req.setTimeout(10000, () => {
      console.error(`❌ ${testConfig.method} 请求超时`);
      req.destroy();
      reject(new Error('请求超时'));
    });

    // 发送请求数据
    if (testConfig.data) {
      req.write(testConfig.data);
    }
    
    req.end();
  });
}

async function runTests() {
  console.log('🧪 开始测试各种HTTP方法...\n');
  
  for (const testConfig of testRequests) {
    try {
      await sendRequest(testConfig);
      console.log(''); // 空行分隔
      
      // 等待1秒再发送下一个请求
      await new Promise(resolve => setTimeout(resolve, 1000));
    } catch (error) {
      console.error(`测试 ${testConfig.method} 失败:`, error.message);
      console.log(''); // 空行分隔
    }
  }
  
  console.log('🎉 所有测试完成！');
  console.log('💡 请检查network-firewall-nodejs控制台输出，确认所有请求都被正确拦截');
}

// 运行测试
runTests().catch(console.error); 